package com.ffcs.web.services;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ffcs.web.daos.implementations.CounselorDao;
import com.ffcs.web.daos.implementations.WechatCityDao;
import com.ffcs.web.model.dto.DirectionString;
import com.ffcs.web.model.entity.Counselor;
import com.ffcs.web.model.entity.PingLun;
import com.ffcs.web.model.entity.WechatCity;
import com.ffcs.web.model.entity.WxUser;
import com.ffcs.web.model.requests.AddCounseRequest;
import com.ffcs.web.model.requests.CounselorListRequest;
import com.ffcs.web.utils.ChinaeseUtil;
import com.ffcs.web.utils.Md5Tool;

@Service
public class CounselorService {

	@Autowired
	private CounselorDao counselorDao;
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private WechatCityDao wechatCityDao;
	
	/**
	 * 注册心理咨询师
	 * @param addCounseRequest
	 */
	@Transactional
	public void addCounse(AddCounseRequest addCounseRequest,String personHeadUrl) {
		List<Counselor> list=counselorDao.findByPropertyName("counseTel",addCounseRequest.getCounseTel());
		if(list.size()==0){
			Counselor counselor=new Counselor();
			counselor.setAddTime(new Date());
			counselor.setCounseName(ChinaeseUtil.CharTOChinaese(addCounseRequest.getCounseName()));
			counselor.setCounsePwd(Md5Tool.EncoderMd5(addCounseRequest.getCounsePwd()));
			counselor.setCounseStatus((short)0);
			counselor.setCounseWorkStatus((short)0);
			counselor.setCounseSuccessCount(0);
			counselor.setCounseTel(addCounseRequest.getCounseTel());
			counselor.setCounseType(addCounseRequest.getCounseType()+",4");
			counselor.setDoctorProve("");
			counselor.setGoodDirection(addCounseRequest.getGoodDirection());
			counselor.setIsFreeAsk((short)1);	
			counselor.setIsReceive((short)1);
			if(addCounseRequest.getIsService15()!=null){
				counselor.setIsService15((short)1);
				counselor.setServicePrice15(Double.parseDouble(addCounseRequest.getServicePrice15()));
			}
			if(addCounseRequest.getIsService40()!=null){
				counselor.setIsService40((short)1);
				counselor.setServicePrice40(Double.parseDouble(addCounseRequest.getServicePrice40()));
			}
			counselor.setLastLoginTime(new Date());
			counselor.setPersonHead(personHeadUrl);
			counselor.setProfessional(ChinaeseUtil.CharTOChinaese(addCounseRequest.getProfessional()));
			counselor.setProName(ChinaeseUtil.CharTOChinaese(addCounseRequest.getProName()));
			counselor.setReceiveTotal(0d);
			counselor.setRecommenGrade("0");
			counselor.setServiceCity(ChinaeseUtil.CharTOChinaese(addCounseRequest.getServiceCity()));
			counselorDao.save(counselor);
		}else{
			Counselor counselor=list.get(0);
			if(counselor.getIsFreeAsk()==1){
				counselor.setCounseType(addCounseRequest.getCounseType()+",4");
			}else{
				counselor.setCounseType(addCounseRequest.getCounseType());
			}
			counselor.setDoctorProve("");
			counselor.setGoodDirection(addCounseRequest.getGoodDirection());
			counselor.setIsReceive((short)1);
			if(addCounseRequest.getIsService15()!=null){
				counselor.setIsService15((short)1);
				counselor.setServicePrice15(Double.parseDouble(addCounseRequest.getServicePrice15()));
			}
			if(addCounseRequest.getIsService40()!=null){
				counselor.setIsService40((short)1);
				counselor.setServicePrice40(Double.parseDouble(addCounseRequest.getServicePrice40()));
			}
			if(!"0".equals(personHeadUrl)){
				counselor.setPersonHead(personHeadUrl);
			}
			counselor.setProfessional(ChinaeseUtil.CharTOChinaese(addCounseRequest.getProfessional()));
			counselor.setProName(ChinaeseUtil.CharTOChinaese(addCounseRequest.getProName()));
			counselor.setServiceCity(ChinaeseUtil.CharTOChinaese(addCounseRequest.getServiceCity()));
			counselorDao.save(counselor);
		}
	}

	/**
	 * 号码判重
	 * @param counseTel
	 * @return
	 */
	public boolean isRegist(String counseTel) {		
		List<Counselor> list=counselorDao.findByPropertyName("counseTel",counseTel);
		if(list.size()==0){
			return true;
		}else{
			return false;
		}
	}

	/**
	 * 我的资料
	 * @param counseTel
	 * @return
	 */
	public Counselor getCounselor(String counseTel) {
		List<Counselor> list=counselorDao.findByPropertyName("counseTel",counseTel);
		return list.get(0);
	}
	/**
	 * 我的资料
	 * @param counseTel
	 * @return
	 */
	public Counselor getCounselor2(String id) {
		return counselorDao.get(Integer.parseInt(id));
	}

	/**
	 * 获取咨询师列表
	 * @param counselorListRequest
	 * @return
	 */
	public List<Counselor> getCounseList(
			CounselorListRequest counselorListRequest) {
		StringBuilder sql=new StringBuilder("select * from wechat_counselor t where counseWorkStatus=1 and counseStatus=1");
		
		if (StringUtils.isNotBlank(counselorListRequest.getTxtsearch())) {
			
			String txtsearch=counselorListRequest.getTxtsearch();
			if(!ChinaeseUtil.isChineseChar(txtsearch)){
				try {
					txtsearch=new String(txtsearch.getBytes("ISO-8859-1"),"UTF-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			
			sql.append(" and (t.counseName like '%"+txtsearch+"%'");
			
			String txtsearchTemp="";
			
			if(txtsearch.contains("视频")){
				txtsearchTemp="3";
				sql.append(" or t.counseType like '%"+txtsearchTemp+"%'");
			}else if(txtsearch.contains("电话")){
				txtsearchTemp="1";
				sql.append(" or t.counseType like '%"+txtsearchTemp+"%'");
			}else if(txtsearch.contains("面对")){
				txtsearchTemp="2";
				sql.append(" or t.counseType like '%"+txtsearchTemp+"%'");
			}
			
			sql.append(" or t.professional like '%"+txtsearch+"%'");
			
			String drectSql="select id from wechat_direction where directionName like '%"+txtsearch+"%'";
			System.out.println("drectSql="+drectSql);
			List<DirectionString> directionStringList=jdbcTemplate.query(drectSql, new BeanPropertyRowMapper<DirectionString>(DirectionString.class));
			if(directionStringList.size()==1){
				sql.append(" or t.goodDirection like '%"+directionStringList.get(0).getId()+"%'");
			}else if(directionStringList.size()==2){
				sql.append(" or t.goodDirection like '%"+directionStringList.get(0).getId()+"%'");
				sql.append(" or t.goodDirection like '%"+directionStringList.get(1).getId()+"%'");
			}
			
			sql.append(" or t.serviceCity like '%"+txtsearch+"%'");
			sql.append(")");
		}
		
		if (StringUtils.isNotBlank(counselorListRequest.getCityName())) {
			
			String cityName="";
			if(counselorListRequest.getCityName().length()>2){
				try {
					cityName=new String(counselorListRequest.getCityName().getBytes("ISO-8859-1"),"UTF-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else{
				cityName=counselorListRequest.getCityName();
			}
			
			
			sql.append(" and t.serviceCity like '%"+cityName+"%'");
		}
		if (StringUtils.isNotBlank(counselorListRequest.getCounseType())) {
			String counseType=counselorListRequest.getCounseType();
			try {
				if(!counseType.equals("视频咨询") && !counseType.equals("电话咨询") && !counseType.equals("面对面咨询")){
					counseType=new String(counseType.getBytes("ISO-8859-1"),"UTF-8");
				}
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			String counseTypeTemp="";
			if(counseType.equals("视频咨询")){
				counseTypeTemp="3";
			}else if(counseType.equals("电话咨询")){
				counseTypeTemp="1";
			}else{
				counseTypeTemp="2";
			}
			
			sql.append(" and t.counseType like '%"+counseTypeTemp+"%'");
		}
		
		if (StringUtils.isNotBlank(counselorListRequest.getGoodDirection())) {
			String goodDirection=counselorListRequest.getGoodDirection();
			
			if(!ChinaeseUtil.isChineseChar(goodDirection)){
				try {
					goodDirection=new String(goodDirection.getBytes("ISO-8859-1"),"UTF-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			if(goodDirection.equals("1")){
				goodDirection="学业倦怠";
			}
			if(goodDirection.equals("2")){
				goodDirection="亲子关系";
			}
			if(goodDirection.equals("3")){
				goodDirection="教育理念";
			}
			if(goodDirection.equals("4")){
				goodDirection="学习习惯";
			}
			if(goodDirection.equals("5")){
				goodDirection="人际关系";
			}
			if(goodDirection.equals("6")){
				goodDirection="沉迷网络";
			}
			if(goodDirection.equals("7")){
				goodDirection="情绪管理";
			}
			if(goodDirection.equals("8")){
				goodDirection="自控能力";
			}
			
			String drectSql="select id from wechat_direction where directionName like '%"+goodDirection+"%'";
			System.out.println("drectSql="+drectSql);
			List<DirectionString> directionStringList=jdbcTemplate.query(drectSql, new BeanPropertyRowMapper<DirectionString>(DirectionString.class));
			if(directionStringList.size()==0){
			}else if(directionStringList.size()==1){
				sql.append(" and t.goodDirection like '%"+directionStringList.get(0).getId()+"%'");
			}else{
				sql.append(" and (t.goodDirection like '%"+directionStringList.get(0).getId()+"%'");
				sql.append(" or t.goodDirection like '%"+directionStringList.get(1).getId()+"%')");
			}
		}
		sql.append(" order by ");
		
		if (StringUtils.isNotBlank(counselorListRequest.getSort()) && counselorListRequest.getSort().equals("1")) {
			sql.append(" t.servicePrice15 asc,");
		}
		
		if (StringUtils.isNotBlank(counselorListRequest.getSort()) && counselorListRequest.getSort().equals("0")) {
			sql.append(" t.servicePrice40 desc,");
		}
		
		sql.append(" t.recommenGrade desc ,counseSuccessCount desc,addTime desc");
		System.out.println("sql="+sql.toString());
		return jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<Counselor>(Counselor.class));
	}

	public List<PingLun> getPinglun(String picNewsId) {
		String sql="select p.*,u.headimgurl from wechat_PingL p,wechat_user u where p.userId=u.id and p.picNewsId="+picNewsId+" order by p.addTime desc";
		return jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<PingLun>(PingLun.class));
	}

	public void addPingLun(String content, String picNewsId, WxUser wxUser,String id) {
		String sql="";
		if(!id.equals("null")){
			sql="insert into wechat_PingL (picNewsId,userId,userName,beiUserId,beiPingId,beiUserName,addTime,beiPingLCnt,content)";
			sql+="values('"+picNewsId+"','"+wxUser.getId()+"','"+wxUser.getNickname()+"',(select p1.userId from wechat_PingL p1 where p1.id="+id+"),"+id+",(select p2.userName from wechat_PingL p2 where p2.id="+id+"),now(),0,'"+content+"')";
			
			String sql2="update wechat_PingL set beiPingLCnt=beiPingLCnt+1 where id="+id;
			jdbcTemplate.update(sql2);
			
		}else{
			sql="insert into wechat_PingL (picNewsId,userId,userName,addTime,beiPingLCnt,content)";
			sql+="values('"+picNewsId+"','"+wxUser.getId()+"','"+wxUser.getNickname()+"',now(),0,'"+content+"')";	
		}
		jdbcTemplate.update(sql);
	}

	@Transactional
	public boolean checkPassword(String tel, String password) {
		
		Counselor counExample=new Counselor();
		counExample.setCounseTel(tel);
		counExample.setCounsePwd(Md5Tool.EncoderMd5(password));
		counExample.setCounseStatus((short)1);
		counExample.setCounseWorkStatus((short)1);
		List<Counselor> list=counselorDao.findByExample(counExample);
		if(list.size()>0){
			Counselor counselor1=list.get(0);
			counselor1.setLastLoginTime(new Date());
			counselorDao.save(counselor1);
			System.out.println("咨询师:"+tel+"--->登陆成功，更新最新登录时间");
			return true;
		}
		return false;
	}

	/**
	 * 修改密码
	 * @param tel
	 * @param password
	 * @return
	 */
	@Transactional
	public boolean updatePassword(String tel, String password) {
		Counselor counExample=new Counselor();
		counExample.setCounseTel(tel);
		List<Counselor> list=counselorDao.findByExample(counExample);
		if(list.size()>0){
			Counselor coun=list.get(0);
			coun.setCounsePwd(Md5Tool.EncoderMd5(password));
			counselorDao.save(coun);
			return true;
		}
		return false;
	}
}
